package com.mingren.api.imagesearch.sub;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.mingren.exception.BusinessException;
import com.mingren.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取百度以图搜图的页面地址 step1
 */
@Slf4j
public class GetImagePageUrlApi {

    /**
     * 获取图片页面地址
     * @param imageUrl:传入的图片地址
     * @return
     */
    public static String getImagePageUrl(String imageUrl) {
        // 1. 准备请求参数 -> 页面载荷
        Map<String, Object> formData = new HashMap<>();
        formData.put("image", imageUrl);
        formData.put("tn", "pc");
        formData.put("from", "pc");
        formData.put("image_source", "PC_UPLOAD_URL");
        // 获取当前时间戳
        long uptime = System.currentTimeMillis();
        // 请求地址
        String url = "https://graph.baidu.com/upload?uptime=" + uptime;

        try {
            // 2. 发送 POST 请求到百度接口
            HttpResponse response = HttpRequest.post(url)
                    // 这里需要指定acs-token 不然会响应系统异常
                    .header("acs-token", RandomUtil.randomString(1)) //指定acs-token
                    .form(formData)
                    .timeout(5000)
                    .execute();

            // 判断响应状态
            if (HttpStatus.HTTP_OK != response.getStatus()) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口调用失败");
            }
            // 解析响应 获取响应结果
            //{"status":0,"msg":"Success",
            // "data":{"url":"https://graph.baidu.com/s?card_key=\u0026entrance=GENERAL\u0026extUiData%5BisLogoShow%5D=1\u0026f=all\u0026isLogoShow=1\u0026session_id=6316470086532894260\u0026sign=12185e97cd54acd88139901741265957\u0026tpl_from=pc","sign":"12185e97cd54acd88139901741265957"}}
            String responseBody = response.body();
            Map<String, Object> result = JSONUtil.toBean(responseBody, Map.class);

            // 3. 处理响应结果
            if (result == null || !Integer.valueOf(0).equals(result.get("status"))) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口调用失败");
            }
            //获取data数据
            Map<String, Object> data = (Map<String, Object>) result.get("data");
            //获取url->下方进行解码
            String rawUrl = (String) data.get("url");
            // 对 URL 进行解码 上面获取的url是编码的 需要解码请求
            String searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);
            // 如果 URL 为空
            // 得到url : https://graph.baidu.com/s?card_key=&entrance=GENERAL&extUiData[isLogoShow]=1&f=all&isLogoShow=1&session_id=7375418200918191941&sign=1218ce97cd54acd88139901741266583&tpl_from=pc
            if (StrUtil.isBlank(searchResultUrl)) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "未返回有效结果");
            }
            //得到搜图的页面url
            return searchResultUrl;
        } catch (Exception e) {
            log.error("调用百度搜图接口失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "搜索失败");
        }
    }

    public static void main(String[] args) {
        // 测试以图搜图功能
        String imageUrl = "https://www.codefather.cn/logo.png";
        String result = getImagePageUrl(imageUrl);
        System.out.println("搜索成功，结果 URL：" + result);
    }
}
